package io.narayana.txdemo.jms;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * @author machinly
 * @date 16/4/20
 * @mail machinly@outlook.com
 */
public class WildFlyJmsQueueSender {

    private static InitialContext ic = null;
    private static WildFlyJmsQueueSender wjqs;
    private Integer count = 0;

    private QueueConnectionFactory qconFactory;
    private QueueConnection qcon;
    private QueueSession qsession;
    private QueueSender qsender;
    private TextMessage msg;

    public static void main(String[] args) throws Exception {
        WildFlyJmsQueueSender.getInstance().send("machinly");
        WildFlyJmsQueueSender.getInstance().send("machinly1");
        WildFlyJmsQueueSender.getInstance().send("machinly2");
        WildFlyJmsQueueSender.getInstance().send("machinly3");
        WildFlyJmsQueueSender.getInstance().send("machinly3");
    }

    public static WildFlyJmsQueueSender getInstance() {
        if (wjqs == null) {
            wjqs = new WildFlyJmsQueueSender();
        }
        return wjqs;
    }

    private WildFlyJmsQueueSender() {
        try {
            ic = WildFlyJmsQueue.getInitialContext();
            qconFactory = (QueueConnectionFactory) ic.lookup(QueueConst.JMS_CONNECTION_FACTORY_JNDI);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }


    public void send(String msg) {
        try {
            this.start(ic, QueueConst.JMS_QUEUE_JNDI);
            this.send(msg, count);
            count++;
            this.close();
        } catch (JMSException | NamingException e) {
            e.printStackTrace();
        }
    }

    private void start(Context ctx, String queueName) throws JMSException, NamingException {
        qcon = qconFactory.createQueueConnection(QueueConst.JMS_USERNAME, QueueConst.JMS_PASSWORD);
        qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = (Queue) ctx.lookup(queueName);
        qsender = qsession.createSender(queue);
        msg = qsession.createTextMessage();
        qcon.start();
    }

    private void send(String message, int counter) throws JMSException {
        msg.setText(message);
        msg.setIntProperty("counter", counter);
        qsender.send(msg);
    }

    private void close() throws JMSException {
        qsender.close();
        qsession.close();
        qcon.close();
    }

}
